"""
管理后台路由模块
处理管理员功能
"""
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify
from flask_login import login_required, current_user

from app import db
from app.models.user import User
from app.models.forum import Post, Comment, Category
from app.models.chat import ChatRoom, Message
from app.auth.decorators import admin_required, handle_exceptions, permission_required
from app.utils.helpers import format_timestamp

admin_bp = Blueprint('admin', __name__, url_prefix='/admin')

@admin_bp.before_request
@login_required
@admin_required
def before_admin_request():
    """
    管理后台请求前检查
    确保用户是管理员
    """
    pass

@admin_bp.route('/')
def dashboard():
    """
    管理后台仪表板
    """
    # 获取基本统计
    stats = {
        'users': {
            'total': User.query.count(),
            'active': User.query.filter_by(is_active=True).count(),
            'online': User.query.filter_by(is_online=True).count(),
            'new_today': User.query.filter(
                User.created_at >= db.func.current_date()
            ).count()
        },
        'forum': {
            'posts': Post.query.filter_by(is_published=True).count(),
            'comments': Comment.query.count(),
            'categories': Category.query.filter_by(is_active=True).count()
        },
        'chat': {
            'rooms': ChatRoom.query.filter_by(is_active=True).count(),
            'messages': Message.query.count()
        }
    }
    
    # 获取最新活动
    recent_users = User.query.order_by(User.created_at.desc()).limit(5).all()
    recent_posts = Post.query.order_by(Post.created_at.desc()).limit(5).all()
    
    return render_template('admin/dashboard.html',
                         stats=stats,
                         recent_users=recent_users,
                         recent_posts=recent_posts)

@admin_bp.route('/users')
def users():
    """
    用户管理
    """
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '').strip()
    role_filter = request.args.get('role', '')
    
    query = User.query
    
    # 搜索过滤
    if search:
        query = query.filter(
            db.or_(
                User.username.ilike(f'%{search}%'),
                User.email.ilike(f'%{search}%')
            )
        )
    
    # 角色过滤
    if role_filter:
        query = query.filter_by(role=role_filter)
    
    # 分页
    users_pagination = query.order_by(User.created_at.desc())\
        .paginate(page=page, per_page=20, error_out=False)
    
    return render_template('admin/users.html',
                         users=users_pagination.items,
                         pagination=users_pagination,
                         search=search,
                         role_filter=role_filter)

@admin_bp.route('/users/<int:user_id>')
def user_detail(user_id):
    """
    用户详情
    """
    user = User.query.get_or_404(user_id)
    
    # 获取用户活动统计
    user_posts = Post.query.filter_by(author_id=user_id).count()
    user_comments = Comment.query.filter_by(author_id=user_id).count()
    
    return render_template('admin/user_detail.html',
                         user=user,
                         user_posts=user_posts,
                         user_comments=user_comments)

@admin_bp.route('/users/<int:user_id>/edit', methods=['GET', 'POST'])
@handle_exceptions
def edit_user(user_id):
    """
    编辑用户
    """
    user = User.query.get_or_404(user_id)
    
    if request.method == 'GET':
        return render_template('admin/edit_user.html', user=user)
    
    # POST请求处理用户编辑
    try:
        data = request.form
        
        # 更新基本信息
        if data.get('username') and data['username'] != user.username:
            from app.utils.helpers import validate_username
            if not validate_username(data['username']):
                flash('用户名格式不正确', 'danger')
                return redirect(url_for('admin.edit_user', user_id=user_id))
            
            if User.query.filter_by(username=data['username']).first():
                flash('该用户名已被使用', 'danger')
                return redirect(url_for('admin.edit_user', user_id=user_id))
            
            user.username = data['username']
        
        if data.get('email') and data['email'] != user.email:
            from app.utils.helpers import validate_email
            if not validate_email(data['email']):
                flash('邮箱格式不正确', 'danger')
                return redirect(url_for('admin.edit_user', user_id=user_id))
            
            if User.query.filter_by(email=data['email']).first():
                flash('该邮箱已被使用', 'danger')
                return redirect(url_for('admin.edit_user', user_id=user_id))
            
            user.email = data['email']
        
        # 更新角色
        if data.get('role') in ['user', 'moderator', 'admin']:
            user.role = data['role']
        
        # 更新状态
        user.is_active = bool(data.get('is_active'))
        
        # 更新其他信息
        if 'bio' in data:
            user.bio = data['bio'][:500]
        
        if 'avatar_url' in data:
            user.avatar_url = data['avatar_url']
        
        db.session.commit()
        
        flash('用户信息更新成功', 'success')
        return redirect(url_for('admin.user_detail', user_id=user_id))
    
    except Exception as e:
        db.session.rollback()
        flash('用户信息更新失败', 'danger')
        return redirect(url_for('admin.edit_user', user_id=user_id))

@admin_bp.route('/users/<int:user_id>/delete', methods=['POST'])
@handle_exceptions
def delete_user(user_id):
    """
    删除用户
    """
    user = User.query.get_or_404(user_id)
    
    # 不能删除自己
    if user.id == current_user.id:
        return jsonify({
            'success': False,
            'message': '不能删除自己的账户'
        }), 400
    
    try:
        # 在实际应用中，这里应该进行软删除或数据清理
        # 现在只是简单删除
        db.session.delete(user)
        db.session.commit()
        
        flash('用户删除成功', 'success')
        return jsonify({
            'success': True,
            'message': '用户删除成功',
            'redirect_url': url_for('admin.users')
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': '用户删除失败'
        }), 500

@admin_bp.route('/posts')
def posts():
    """
    帖子管理
    """
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '').strip()
    status_filter = request.args.get('status', '')
    
    query = Post.query
    
    # 搜索过滤
    if search:
        query = query.filter(
            db.or_(
                Post.title.ilike(f'%{search}%'),
                Post.content.ilike(f'%{search}%')
            )
        )
    
    # 状态过滤
    if status_filter == 'published':
        query = query.filter_by(is_published=True)
    elif status_filter == 'unpublished':
        query = query.filter_by(is_published=False)
    
    # 分页
    posts_pagination = query.order_by(Post.created_at.desc())\
        .paginate(page=page, per_page=20, error_out=False)
    
    return render_template('admin/posts.html',
                         posts=posts_pagination.items,
                         pagination=posts_pagination,
                         search=search,
                         status_filter=status_filter)

@admin_bp.route('/posts/<int:post_id>')
def post_detail(post_id):
    """
    帖子详情
    """
    post = Post.query.get_or_404(post_id)
    comments = Comment.query.filter_by(post_id=post_id).all()
    
    return render_template('admin/post_detail.html',
                         post=post,
                         comments=comments)

@admin_bp.route('/posts/<int:post_id>/toggle-publish', methods=['POST'])
@handle_exceptions
def toggle_post_publish(post_id):
    """
    切换帖子发布状态
    """
    post = Post.query.get_or_404(post_id)
    
    post.is_published = not post.is_published
    db.session.commit()
    
    action = '发布' if post.is_published else '取消发布'
    flash(f'帖子已{action}', 'success')
    
    return jsonify({
        'success': True,
        'is_published': post.is_published,
        'message': f'帖子已{action}'
    })

@admin_bp.route('/posts/<int:post_id>/delete', methods=['POST'])
@handle_exceptions
def delete_post_admin(post_id):
    """
    管理员删除帖子
    """
    post = Post.query.get_or_404(post_id)
    
    try:
        # 更新分类帖子计数
        category = Category.query.get(post.category_id)
        if category:
            category.post_count -= 1
        
        # 删除帖子
        db.session.delete(post)
        db.session.commit()
        
        flash('帖子删除成功', 'success')
        return jsonify({
            'success': True,
            'message': '帖子删除成功',
            'redirect_url': url_for('admin.posts')
        })
    
    except Exception as e:
        db.session.rollback()
        return jsonify({
            'success': False,
            'message': '帖子删除失败'
        }), 500

@admin_bp.route('/categories')
def categories():
    """
    分类管理
    """
    categories = Category.query.order_by(Category.created_at.desc()).all()
    return render_template('admin/categories.html', categories=categories)

@admin_bp.route('/categories/create', methods=['GET', 'POST'])
@handle_exceptions
def create_category():
    """
    创建分类
    """
    if request.method == 'GET':
        return render_template('admin/create_category.html')
    
    # POST请求处理分类创建
    try:
        name = request.form.get('name', '').strip()
        description = request.form.get('description', '').strip()
        color = request.form.get('color', '#3498db')
        
        if not name:
            flash('请填写分类名称', 'danger')
            return redirect(url_for('admin.create_category'))
        
        if len(name) > 50:
            flash('分类名称不能超过50个字符', 'danger')
            return redirect(url_for('admin.create_category'))
        
        # 检查分类名是否已存在
        existing_category = Category.query.filter_by(name=name).first()
        if existing_category:
            flash('该分类名已存在', 'danger')
            return redirect(url_for('admin.create_category'))
        
        # 创建分类
        category = Category(
            name=name,
            description=description,
            color=color
        )
        
        db.session.add(category)
        db.session.commit()
        
        flash('分类创建成功', 'success')
        return redirect(url_for('admin.categories'))
    
    except Exception as e:
        db.session.rollback()
        flash('分类创建失败', 'danger')
        return redirect(url_for('admin.create_category'))

@admin_bp.route('/categories/<int:category_id>/edit', methods=['GET', 'POST'])
@handle_exceptions
def edit_category(category_id):
    """
    编辑分类
    """
    category = Category.query.get_or_404(category_id)
    
    if request.method == 'GET':
        return render_template('admin/edit_category.html', category=category)
    
    # POST请求处理分类编辑
    try:
        name = request.form.get('name', '').strip()
        description = request.form.get('description', '').strip()
        color = request.form.get('color', '#3498db')
        is_active = bool(request.form.get('is_active'))
        
        if not name:
            flash('请填写分类名称', 'danger')
            return redirect(url_for('admin.edit_category', category_id=category_id))
        
        # 检查分类名是否重复（排除自己）
        existing_category = Category.query.filter(
            Category.name == name,
            Category.id != category_id
        ).first()
        
        if existing_category:
            flash('该分类名已存在', 'danger')
            return redirect(url_for('admin.edit_category', category_id=category_id))
        
        # 更新分类
        category.name = name
        category.description = description
        category.color = color
        category.is_active = is_active
        
        db.session.commit()
        
        flash('分类更新成功', 'success')
        return redirect(url_for('admin.categories'))
    
    except Exception as e:
        db.session.rollback()
        flash('分类更新失败', 'danger')
        return redirect(url_for('admin.edit_category', category_id=category_id))

@admin_bp.route('/chat/rooms')
def chat_rooms():
    """
    聊天室管理
    """
    page = request.args.get('page', 1, type=int)
    search = request.args.get('search', '').strip()
    
    query = ChatRoom.query
    
    # 搜索过滤
    if search:
        query = query.filter(ChatRoom.name.ilike(f'%{search}%'))
    
    # 分页
    rooms_pagination = query.order_by(ChatRoom.created_at.desc())\
        .paginate(page=page, per_page=20, error_out=False)
    
    return render_template('admin/chat_rooms.html',
                         rooms=rooms_pagination.items,
                         pagination=rooms_pagination,
                         search=search)

@admin_bp.route('/system/stats')
def system_stats():
    """
    系统统计
    """
    from datetime import datetime, timedelta
    
    # 获取最近30天的数据
    thirty_days_ago = datetime.utcnow() - timedelta(days=30)
    
    # 用户注册统计
    user_registrations = db.session.query(
        db.func.date(User.created_at).label('date'),
        db.func.count(User.id).label('count')
    ).filter(User.created_at >= thirty_days_ago)\
     .group_by(db.func.date(User.created_at))\
     .all()
    
    # 帖子发布统计
    post_publications = db.session.query(
        db.func.date(Post.created_at).label('date'),
        db.func.count(Post.id).label('count')
    ).filter(Post.created_at >= thirty_days_ago)\
     .group_by(db.func.date(Post.created_at))\
     .all()
    
    # 转换为图表数据格式
    chart_data = {
        'user_registrations': [
            {'date': str(reg.date), 'count': reg.count}
            for reg in user_registrations
        ],
        'post_publications': [
            {'date': str(pub.date), 'count': pub.count}
            for pub in post_publications
        ]
    }
    
    return render_template('admin/system_stats.html', chart_data=chart_data)

@admin_bp.route('/system/settings', methods=['GET', 'POST'])
@handle_exceptions
def system_settings():
    """
    系统设置
    """
    if request.method == 'GET':
        # 获取当前设置（这里只是示例）
        settings = {
            'site_name': 'SteHub',
            'site_description': '学生交流平台',
            'allow_registration': True,
            'require_email_verification': False,
            'max_file_size': 16,  # MB
            'maintenance_mode': False
        }
        
        return render_template('admin/system_settings.html', settings=settings)
    
    # POST请求处理设置更新
    try:
        # 这里应该更新数据库或配置文件中的设置
        # 现在只是示例
        
        flash('系统设置已更新', 'success')
        return redirect(url_for('admin.system_settings'))
    
    except Exception as e:
        flash('系统设置更新失败', 'danger')
        return redirect(url_for('admin.system_settings'))

# API 路由
@admin_bp.route('/api/stats')
def api_admin_stats():
    """
    API: 管理后台统计
    """
    from datetime import datetime, timedelta
    
    # 今日统计
    today = datetime.utcnow().date()
    today_start = datetime(today.year, today.month, today.day)
    
    stats = {
        'users': {
            'total': User.query.count(),
            'new_today': User.query.filter(User.created_at >= today_start).count(),
            'online': User.query.filter_by(is_online=True).count()
        },
        'forum': {
            'posts_total': Post.query.filter_by(is_published=True).count(),
            'posts_today': Post.query.filter(
                Post.created_at >= today_start,
                Post.is_published == True
            ).count(),
            'comments_total': Comment.query.count(),
            'comments_today': Comment.query.filter(
                Comment.created_at >= today_start
            ).count()
        },
        'chat': {
            'rooms_active': ChatRoom.query.filter_by(is_active=True).count(),
            'messages_today': Message.query.filter(
                Message.created_at >= today_start
            ).count()
        }
    }
    
    return jsonify({
        'success': True,
        'stats': stats
    })